<?php

namespace App\Http\Controllers\Common;

use App\Helpers\ImgCompress;
use App\Http\Controllers\Controller;
use App\Models\Image;
use Illuminate\Http\Request;

class ImageController extends Controller
{
    public function upload(Request $request)
    {
        $user = $request->get('user', 0);
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $f = $request->file('file');
            $extension = $f->extension();
            $name = date('Ymd');
            $path = $f->store($name);
            $fileTypes = config('common.fileTypes');
            if (in_array($extension, $fileTypes['images'])) {
                $type = 1;
            } else {
                $type = 0;
            }

            $file = new Image();
            $file['user'] = $user;
            $file['path'] = $path;
            $file['type'] = $type;
            $file->save();
            // 压缩图片
            $src = public_path() . '/uploads/' . $path;
            $img = new ImgCompress($src);
            $img->compressImg($src);
            return jsonResponse(1, $file);
        }
        return jsonResponse(5001);
    }
}
